import { useRef, useState } from "react";
import styled from "styled-components";
import { Breadcrumb, Button, Col, Flex, Form, message, Select, Space } from "antd";
import { EditableProTable, ProForm, ProFormItem, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import { useParams, useRouter, useSearchParams } from "@/router/hooks";
import ProFormCode from "@/components/form/ProFormCode";
import { Link } from "react-router-dom";
import { useDictOptions } from "@/hooks";
import { CircleLoading } from "@/components/loading";
import { useQuery } from "@tanstack/react-query";

import { dmServiceAdd, dmServiceDetail, dmServiceEdit } from "@/api/sharing/dmService";
import DataSourceSelect from "../dataSource/modules/DataSourceSelect";


const DmServiceEdit = () => {
  const formRef = useRef();
  const { id } = useParams();
  const router = useRouter();
  const { data: paramTypeOptions } = useDictOptions(['param_type'])
  const [editableInfoKeys, setEditableInfoKeys] = useState([]);
  const [editableQueryKeys, setEditableQueryKeys] = useState([]);

  const { data: fullData, isFetching, refetch } = useQuery({
    queryKey: ['page-DmServiceEdit-dmServiceDetail', id],
    queryFn: () => {
      return dmServiceDetail({ id: id }).then((res) => {
        if (res?.result?.itemList) {
          setEditableInfoKeys(old => ([].concat(old, res?.result?.itemList.map(d => d.id))))
        }
        if (res?.result?.queryParamList) {
          setEditableQueryKeys(old => ([].concat(old, res?.result?.queryParamList.map(d => d.id))))
        }
        return res?.result ? {
          ...res?.result.baseData,
          itemList: res?.result.itemList.map(d => ({ ...d, key: d.id })),
          queryParamList: res?.result.queryParamList.map(d => ({ ...d, key: d.id })),
        } : { itemList: [], queryParamList: [] }
      })
    },
    enabled: !!id
  })

  const infoItemColumns = [
    {
      title: '字段名称',
      dataIndex: 'paramName',
      formItemProps: {
        rules: [{ required: true, message: '请填写字段名称' }]
      },
    },
    {
      title: '字段类型',
      dataIndex: 'paramType',
      valueType: 'select',
      fieldProps: {
        options: paramTypeOptions
      },
      formItemProps: {
        rules: [{ required: true, message: '请选择字段类型' }]
      },
    },
    {
      title: '字段长度',
      dataIndex: 'paramLength',
      valueType: 'digit',
      fieldProps: { min: 0, precision: 0 }
    },
    {
      title: '字段描述',
      dataIndex: 'paramRemark',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 90,
      render: (text, record) => [],
    },
  ]

  const queryParamColumns = [
    {
      title: '参数名称',
      dataIndex: 'paramName',
      formItemProps: {
        rules: [{ required: true, message: '此项为必填项' }],
      },

    },
    {
      title: '参数类型',
      dataIndex: 'paramType',
      valueType: 'select',
      fieldProps: {
        options: paramTypeOptions
      },
      formItemProps: {
        rules: [{ required: true, message: '请选择参数类型' }]
      },
    },
    {
      title: '参数描述',
      dataIndex: 'paramRemark',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 90,
      render: (text, record) => [],
    },
  ]
  const handleSubmit = (values) => {
    let api_fun = values.id ? dmServiceEdit : dmServiceAdd
    const params = {
      baseData: {
        id: values.id,
        remark: values.remark,
        serviceName: values.serviceName,
        sqlText: values.sqlText,
        dataSourceId: values.dataSourceId,
      },
      itemList: values.itemList,
      queryParamList: values.queryParamList
    }
    api_fun(params).then(res => {
      if (res.code === 200) {
        message.success('提交成功');
        router.push('/dmService')
        // router.back();
      }
    })
  }

  if (isFetching) {
    return <CircleLoading target={'parent'}></CircleLoading>
  }

  return (<StyleWrap className="dm-service-edit">
    <div className="page-breadcrumb">
      <Breadcrumb
        items={[
          {
            title: <Link to="/dmService">达梦服务</Link>,
          },
          {
            title: id ? '编辑服务' : '新建服务',
          }
        ]}
      />
    </div>
    <ProForm
      formRef={formRef}
      layout={'horizontal'}
      grid={true}
      initialValues={{
        itemList: [],
        queryParamList: [],
        ...(fullData || {})
      }}
      submitter={{
        render: (props, doms) => {
          return <Flex justify={'start'} style={{ paddingLeft: '120px' }}>
            <Space><Button onClick={router.back}>取消</Button>{doms[1]}</Space>
          </Flex>;
        },
      }}
      onFinish={handleSubmit}
    >
      <ProFormItem name="id" hidden></ProFormItem>
      <ProFormText name="serviceName" label="服务名称" rules={[{ required: true, message: '请输入服务名称' }]} />
      <Col span={24}>
        <ProFormItem name="dataSourceId" label="数据源" rules={[{ required: true, message: '数据源不能为空' }]}>
          <DataSourceSelect placeholder={'请选择数据源'} />
        </ProFormItem>
      </Col>
      <EditableProTable
        rowKey="key"
        toolBarRender={false}
        columns={infoItemColumns}
        formItemProps={{ label: '信息项', rules: [{ required: true, message: '查询参数不能为空' }] }}
        name={'itemList'}
        recordCreatorProps={{
          newRecordType: 'dataSource',
          position: 'bottom',
          record: () => ({
            key: Date.now(),
          }),
        }}
        editable={{
          type: 'multiple',
          editableKeys: editableInfoKeys,
          onChange: setEditableInfoKeys,
          actionRender: (row, config) => {
            return [<a key="delete" onClick={() => {
              formRef.current?.setFieldValue(config.tableName, formRef.current?.getFieldValue(config.tableName).filter((item) => item.key !== row.key));
            }}>删除</a>];
          },
        }}
      />
      <EditableProTable
        rowKey="key"
        toolBarRender={false}
        columns={queryParamColumns}
        formItemProps={{
          label: '查询参数',
          rules: [{ required: true, message: '查询参数不能为空' }]
        }}
        name={'queryParamList'}
        recordCreatorProps={{
          newRecordType: 'dataSource',
          position: 'bottom',
          record: () => ({
            key: Date.now(),
          }),
        }}
        editable={{
          type: 'multiple',
          editableKeys: editableQueryKeys,
          onChange: setEditableQueryKeys,
          actionRender: (row, config) => {
            return [<a key="delete" onClick={() => {
              formRef.current?.setFieldValue(config.tableName, formRef.current?.getFieldValue(config.tableName).filter((item) => item.key !== row.key));
            }}>删除</a>];
          },
        }}
      />
      <ProFormCode name="sqlText" label="SQL封装服务" fieldProps={{ height: '300px', lang: 'sql' }} rules={[{ required: true, message: 'SQL 不能为空' }]} />
      <ProFormTextArea name="remark" label="服务描述" />
    </ProForm>
  </StyleWrap>);
}
const StyleWrap = styled.div`
  &.dm-service-edit{
    padding: 16px;
  }
  .steps-wrapper{
    width: 70%;
  }
  .forms-wrapper{
    margin-top: 30px;
  }
 
  .ant-form-item-label{
    width: 120px;
    text-align: right;
  }
  .ant-input-number{
    width: 100%;
  }
`
export default DmServiceEdit;